package com.mchsdk.paysdk.http.request;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.entity.UserRegister;
import com.mchsdk.paysdk.http.RequestUtil;
import com.mchsdk.paysdk.utils.MCErrorCodeUtils;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.VerifyCodeCookisStore;

import org.json.JSONException;
import org.json.JSONObject;

public class CertificateRequest {

	private static final String TAG = "CertificateRequest";

	HttpUtils http;
	Handler mHandler;


	public CertificateRequest(Handler mHandler) {
		http = new HttpUtils();
		if (null != mHandler) {
			this.mHandler = mHandler;
		}

	}
	public void  post(String url, RequestParams params) {
		if (TextUtils.isEmpty(url) || null == params) {
			MCLog.e(TAG, "fun#post url is null add params is null");
			noticeResult(Constant.To_Certificate_FAIL, "url未设或参数为空");
			return;
		}
		MCLog.e(TAG, "fun#post url = " + url);
		http.configCookieStore(VerifyCodeCookisStore.cookieStore);
		http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				MCLog.e(TAG, "fun#responseInfo.result = " + responseInfo.result);
				String response = RequestUtil.getResponse( responseInfo);
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject(response);
					int status = jsonObject.optInt("status");
					if (status == 200 || status == 1){
						String idcard = jsonObject.optString("idcard", "");
						noticeResult(Constant.To_Certificate_SUCCESS, idcard);
					}else {
						String msg;
						if (!TextUtils.isEmpty(jsonObject.optString("return_msg"))) {
							msg = jsonObject.optString("return_msg");
						} else {
							msg = MCErrorCodeUtils.getErrorMsg(status);
						}
						MCLog.e(TAG, "msg:" + msg);
						noticeResult(Constant.To_Certificate_FAIL, msg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
					Log.e(TAG,"解析异常");
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {
				MCLog.e(TAG, "onFailure" + msg);
				MCLog.e(TAG, "onFailure" + error.getExceptionCode());
				MCLog.e(TAG, "onFailure" + error.getLocalizedMessage());
				MCLog.e(TAG, "onFailure" + error.getMessage());
				MCLog.e(TAG, "onFailure" + error.getStackTrace());
				noticeResult(Constant.To_Certificate_FAIL, "网络异常");
			}
		});
	}

	private void noticeResult(int type, Object obj) {
		Message msg = new Message();
		msg.what = type;
		msg.obj = obj;
		if (null != mHandler) {
			mHandler.sendMessage(msg);
		}
	}

}
